// pages/deliver-goods/deliver-goods.js
const app = getApp();
const http = app.http;
const userInfoManager = app.userInfoManager;
import Dialog from 'vant-weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    color: '#000000',
    background: '#ffffff',
    timePopupShow: false,
    searchObject: {
      supplierId: "",
      statusId: 2,
      startTime: "",
      endTime: "",
      campusIds: [],
    },
    viewHeight: "",
    orderList: [],
    isSelected: false, //是否进入选择状态
    gardenPopupShow: false,
    selectDriverShow: false,
    selectDriverId: "", //选择的司机ID
    selectGardenList: [],
    viewPaddingHeight: 0,
    timeText: "今日到货",
    gardenText: "所有园所",
    selectGarden: [], //选择的园所信息
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    allChecked: false, //全选
    schoolList: [],
    driverList: [],
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    }
  },

  /**确认选择时间 */
  confirmTime(event) {
    console.log(event.detail);
    let timeText = "";
    if (event.detail === new Date().getTime()) {
      timeText = "今日到货";
    } else {
      var date = new Date(event.detail);
      let months = (date.getMonth() + 1) <= 9 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      let dates = date.getDate() <= 9 ? "0" + date.getDate() : date.getDate();
      timeText = date.getFullYear() + "-" + months + "-" + dates;
    }
    console.log(timeText);
    this.setData({
      timeText,
      currentDate: event.detail,
      timePopupShow: false
    });
    this.data.searchObject.startTime = timeText + " 00:00:00";
    this.data.searchObject.endTime = timeText + " 23:59:59";
    this.initData();
    this.getSchoolList();
  },
  /**选择园所确定 */
  selectGarden() {
    let gardenText = "";
    if (this.data.selectGarden.length === 1) {
      for (let i = 0; i < this.data.schoolList.length; i++) {
        if (this.data.schoolList[i].schoolId === this.data.selectGarden[0]) {
          gardenText = this.data.schoolList[i].schoolName;
          break;
        }
      }
    } else if (this.data.selectGarden.length === this.data.schoolList.length || this.data.selectGarden.length === 0) {
      gardenText = "所有园所";
    } else {
      gardenText = "多家园所";
    }
    this.setData({
      gardenText,
      gardenPopupShow: false
    });
    this.data.searchObject.campusIds = this.data.selectGarden;
    this.initData();
  },
  clickAddress(e) {
    let order = e.currentTarget.dataset.order;
    Dialog.alert({
      title: order.schoolName,
      message: order.schoolAddr,
      confirmButtonColor: "#21af65",
    }).then(() => {
      // on close
    });
  },
  clickPhone(e) {
    let order = e.currentTarget.dataset.order;
    Dialog.confirm({
      title: order.schoolName,
      message: order.schoolTel + '\n负责人：' + order.adminName,
      showCancelButton: true,
      confirmButtonText: "拨打电话",
      confirmButtonColor: "#21af65",
      cancelButtonColor: "#21af65"
    }).then(() => {
      if (order.schoolTel && order.schoolTel !== "") {
        wx.makePhoneCall({
          phoneNumber: order.schoolTel //仅为示例，并非真实的电话号码
        })
      }
    }).catch(() => {
      // on cancel
    });
  },
  /**选中园所 */
  onSelectChange(event) {
    let index = event.currentTarget.dataset.item;
    console.log(index, this.data.orderList);
    let checked = !this.data.orderList[index].checked;
    this.data.orderList[index].checked = !this.data.orderList[index].checked;

    this.setData({
      orderList: this.data.orderList
    });
    if (checked) {
      this.data.selectGardenList.push(this.data.orderList[index]);
      for (let i = 0; i < this.data.orderList.length; i++) {
        if (!this.data.orderList[i].checked) {
          break;
        }
        if (i === this.data.orderList.length - 1) {
          this.setData({
            allChecked: true
          });
        }
      }
    } else {
      for (let i = 0; i < this.data.selectGardenList.length; i++) {
        if (this.data.orderList[index].orderId === this.data.selectGardenList[i].orderId) {
          this.data.selectGardenList.splice(i, 1);
        }
      }
      this.setData({
        allChecked: false
      });
    }
    console.log(index, this.data.orderList);
  },
  /**全选 */
  onAllSelectChange(event) {
    for (let i = 0; i < this.data.orderList.length; i++) {
      this.data.orderList[i].checked = event.detail;
    }
    this.data.selectGardenList = [];
    if (event.detail) {
      this.data.selectGardenList = this.data.selectGardenList.concat(this.data.orderList);
      // this.data.selectGardenList = Arrays.copyOf(this.data.orderList, this.data.orderList.length);
    }
    this.setData({
      orderList: this.data.orderList,
      allChecked: event.detail
    });
  },
  onChange(event) {
    this.setData({
      selectGarden: event.detail
    });
  },
  /**取消选择园所 */
  cancleSelect() {
    this.setData({
      isSelected: false
    });
  },
  /**选择司机 */
  selectDriver() {
    let personInfo = userInfoManager.getSupplierInfo();
    http.driverList({
      supplierId: personInfo.id
    }).then(res => {
      if (res.code == 0) {
        let driverList = [];
        let drivers = [];
        for (let i = 0; i < res.data.length; i++) {
          res.data[i].isSelect = false;
          if ((i + 1) % 6 === 0) {
            drivers.push(res.data[i]);
            driverList.push(drivers);
            drivers = [];
          } else {
            drivers.push(res.data[i]);
            if (i === res.data.length - 1) {
              driverList.push(drivers);
            }
          }
        }
        this.setData({
          selectDriverShow: true,
          driverList: driverList
        });
      } else {
        wx.showToast({
          duration: 1000,
          icon: 'none',
          title: res.msg
        })
      }
    })

  },
  clickOrder(event) {
    console.log(event.currentTarget);
    wx.navigateTo({
      url: '/pages/deliver-goods/deliver-goods-detail?orderId=' + event.currentTarget.dataset.item,
      success: (result) => {

      },
      fail: (e) => {
        console.log(JSON.stringify(e))
      },
      complete: () => {}
    });
  },
  /**选择司机  */
  clickDriver(event) {
    if (event.currentTarget.dataset.item.isSelect) return;
    for (let i = 0; i < this.data.driverList.length; i++) {
      for (let n = 0; n < this.data.driverList[i].length; n++) {
        if (this.data.driverList[i][n].id === event.currentTarget.dataset.item.id) {
          this.data.driverList[i][n].isSelect = true;
          this.data.selectDriverId = this.data.driverList[i][n].id;
        } else {
          this.data.driverList[i][n].isSelect = false;
        }
      }
    }
    this.setData({
      driverList: this.data.driverList
    });
  },
  /**确认发货 */
  clickSure() {
    if (this.data.selectGardenList.length === 0) {
      wx.showToast({
        duration: 1000,
        icon: 'none',
        title: "请选择订单!"
      })
      return
    }
    if (this.data.selectDriverId === "") {
      wx.showToast({
        duration: 1000,
        icon: 'none',
        title: "请选择一位司机!"
      })
      return
    }
    let updateOrder = [];
    for (let i = 0; i < this.data.selectGardenList.length; i++) {
      updateOrder.push({
        orderId: this.data.selectGardenList[i].orderId,
        newStatus: 3,
        driverId: this.data.selectDriverId
      });
    }
    http.updateOrderStatus(updateOrder).then(res => {
      if (res.code == 0) {
        this.setData({
          selectDriverShow: false,
          isSelected: false
        });
        wx.showToast({
          duration: 3000,
          icon: 'none',
          title: '发货成功'
        })
        setTimeout(() => {
          this.initData();
        }, 3000);

      } else {
        wx.showToast({
          duration: 1000,
          icon: 'none',
          title: res.msg
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(app.globalData.statusBarHeight);
    let viewHeight = (app.globalData.statusBarHeight + 44) + 58;
    this.setData({
      viewHeight
    });
    let personInfo = userInfoManager.getSupplierInfo();
    this.data.searchObject.supplierId = personInfo.id;
    var date = new Date();
    // console.log(date);
    var months = (date.getMonth() + 1) <= 9 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var dates = date.getDate() <= 9 ? "0" + date.getDate() : date.getDate();
    var timeText = date.getFullYear() + "-" + months + "-" + dates;
    this.data.searchObject.startTime = timeText + " 00:00:00";
    this.data.searchObject.endTime = timeText + " 23:59:59";
    this.getSchoolList();
    this.initData();
  },
  getSchoolList() {
    // let data = [];
    // for (let i = 0; i < 11; i++) {
    //   data.push({
    //     schoolId: "123456789",
    //     schoolName: "哈哈哈哈哈哈哈哈哈"
    //   })
    // }
    // this.setData({
    //   schoolList: data
    // });
    http.sendSchool({
      supplierId: this.data.searchObject.supplierId,
      startTime: this.data.searchObject.startTime,
      endTime: this.data.searchObject.endTime
    }).then(res => {
      if (res.code == 0) {
        if (res.data.length > 11) {
          this.data.viewPaddingHeight = this.viewHeight + 10;
        }
        this.setData({
          schoolList: res.data,
          viewPaddingHeight: this.data.viewPaddingHeight
        });
      } else {
        wx.showToast({
          duration: 1000,
          icon: 'none',
          title: res.msg
        })
      }
    })
  },
  /**初始化数据 */
  initData() {
    http.orderList(this.data.searchObject,true).then(res => {
      if (res.code == 0) {
        for (var i = 0; i < res.data.length; i++) {
          res.data[i].categoryslen = Object.getOwnPropertyNames(res.data[i].categorys).length;
          res.data[i].productslen = Object.getOwnPropertyNames(res.data[i].products).length;
          res.data[i].checked = false;
          res.data[i].endTime = res.data[i].arrivalDateEnd.split(" ")[1];
        }
        this.setData({
          orderList: res.data
        });
        // console.log(this.data.orderList);
      } else {
        wx.showToast({
          duration: 1000,
          icon: 'none',
          title: res.msg
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },
  /**我要发货 */
  clickDeliver() {
    this.setData({
      isSelected: true
    });
  },
  /**选择时间 */
  clickTime() {
    let timePopupShow = !this.data.timePopupShow;
    this.setData({
      timePopupShow,
      gardenPopupShow: false
    })
  },
  /**关闭时间组件 */
  onTimePopupClose() {

    this.setData({
      timePopupShow: false
    })
  },

  /**选择园所 */
  clickGarden() {
    let gardenPopupShow = !this.data.gardenPopupShow;
    this.setData({
      timePopupShow: false,
      gardenPopupShow
    })
  },
  /**关闭园所组件 */
  onGarrdenPopupClose() {
    this.setData({
      gardenPopupShow: false
    })
  },

  /**关闭司机组件 */
  onSelectDriverClose() {
    this.setData({
      selectDriverShow: false
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    console.log("AAAAAAAAAAA");
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})